﻿#include "UDropTreeView.h"
#include "CPageCarouse.h"
#include "CNodeCarouse.h"
#include "Global.h"
void UDropTreeView::dragEnterEvent(QDragEnterEvent * event)
{
	if (event->mimeData()->hasFormat("application/x-pageinfo")) 
	{
		event->acceptProposedAction();
	}
}

void UDropTreeView::dragMoveEvent(QDragMoveEvent * event)
{
	if (!event->mimeData()->hasFormat("application/x-pageinfo"))
	{
		clearSelection();
		event->ignore();                // 禁止放
		return;
	}
	QModelIndex index = indexAt(event->pos());
	if (!index.isValid()) {
		event->ignore();
		return;
	}
	QVariant var = index.data(Qt::UserRole);
	void* ptr = var.value<void*>();  // 取出 void* 指针
	if (ptr == nullptr)
	{
		clearSelection();
		event->ignore();                // 禁止放
		return;
	}
	setCurrentIndex(index);
	CBaseCarouse* pCarouse = reinterpret_cast<CBaseCarouse*>(ptr);
	if (pCarouse->getType() == CBaseCarouse::enNodeCarouse)
	{
				
		event->acceptProposedAction();  // 可以放
	}
	else
	{
		event->ignore();                // 禁止放
	}
		
	
}

void UDropTreeView::dropEvent(QDropEvent * event)
{
	if (!event->mimeData()->hasFormat("application/x-pageinfo"))
		return;
	QByteArray data = event->mimeData()->data("application/x-pageinfo");
	QJsonDocument doc = QJsonDocument::fromJson(data);
	QJsonArray array = doc.array();
	QVector<SPageItem>vecPageItem;
	for (const auto& val : array) 
	{
		QJsonObject obj = val.toObject();
		SPageItem info;
		info.sGuid = obj["guid"].toString();
		info.sCardGuid = obj["cardguid"].toString();
		info.nRow = obj["row"].toInt();
		info.nCol = obj["col"].toInt();
		info.nRowSpan = obj["rowspan"].toInt();
		info.nColSpan = obj["colspan"].toInt();
		vecPageItem.push_back(info);
	}
	QModelIndex index = indexAt(event->pos());
	QString sName = event->mimeData()->text();
	QVariant var = index.data(Qt::UserRole);
	void* ptr = var.value<void*>();  // 取出 void* 指针
	if (ptr != nullptr)
	{
		CBaseCarouse *pCarouse = reinterpret_cast<CBaseCarouse*>(ptr);
		if (pCarouse->getType() == CBaseCarouse::enRootCarouse)
		{
			CPageCarouse* pPage = new CPageCarouse(sName, pCarouse);
			pPage->setPageItems(vecPageItem);
			emit sign_addItem(pCarouse);
		}
		else if (pCarouse->getType() == CBaseCarouse::enNodeCarouse )
		{
			CPageCarouse * pPage = new CPageCarouse(sName, pCarouse);
			pPage->setPageItems(vecPageItem);
			emit sign_addItem(pCarouse);
			expand(index);
		}
		else
		{
			CBaseCarouse *pParent = (CBaseCarouse *)pCarouse->getParent();
			if (pParent != NULL)
			{
				CPageCarouse * pPage = new CPageCarouse(sName, pParent);
				pPage->setPageItems(vecPageItem);
				emit sign_addItem(pParent);
			}
		}
	}
	else
	{
		showMessageBox(this, A2T("警告"), A2T("请先选择轮播节点"), 1);
	}
	event->acceptProposedAction();
}
